package co.gov.medellin.sdep.sisdep.jpegcam.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import co.gov.medellin.sdep.sisdep.common.OracleHelper;
import co.gov.medellin.sdep.sisdep.common.SpringAppContext;
import co.gov.medellin.sdep.sisdep.integration.backingbean.IntegrationController;

/**
 * Servlet implementation class PictureCaptureServlet
 */
public class PictureCaptureServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String fileStoreURL = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PictureCaptureServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		fileStoreURL = config.getServletContext().getRealPath("") + "/uploads";
		try {
			File f = new File(fileStoreURL);
			if (!f.exists()) {
				f.mkdirs();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// Se debe obtener el "integrationController" por medio de la Session ya que es inicializado desde el 
			// faces config con alcance de session y NO es un SpringBean para usar el SpringAppContext.
			IntegrationController intCtrl = ((IntegrationController) request.getSession().getAttribute("integrationController"));
			
			if(OracleHelper.isNullorEmpty(intCtrl.getDocumentType())||OracleHelper.isNullorEmpty(intCtrl.getDocumentID())) {
				response.getWriter().print("Indentificaci\u00F3n del Comerciante Incompleta!!");
			} else {
				String snapshotPath = fileStoreURL + "/" + intCtrl.getDocumentType() + "_" + intCtrl.getDocumentID() + ".jpg";
					
				FileOutputStream fileOutputStream = new FileOutputStream(snapshotPath);
				int res;
				while ((res = request.getInputStream().read()) != -1) {
					fileOutputStream.write(res);
				}
				fileOutputStream.close();
				/**
				 * Se retorna el nombre de la imagen almacenada, la ruta:
				 */				
				response.getWriter().print("/uploads/" + intCtrl.getDocumentType() + "_" + intCtrl.getDocumentID() + ".jpg");				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

}
